<?php 
namespace Wdl\model;
use Wdl\validate\ValidateException;
use Wdl\validate\Validate;
use Wdl\helper\FrontHelper;

class favorite extends base
{
    /**添加收藏的 controller action */
    public function add()
    {    
        global $_W, $_GPC;
        $uniacid = $this->uniacid;
        $openid = $this->openid;
        $uid = $this->uid;

        FrontHelper::check_login();
    
        $user= $jsondata = array();         
        if(!empty($openid)){
            $user = pdo_fetch("select ecuid,nickname,mobile, avatar from". tablename("kbwdl_broker")." where uniacid='$uniacid' and openid='$openid' order by id desc");
            $jsondata =  $user;
        }
        
        /* 判断是否收藏过 */ 
        $houseid = intval($_GPC['id']);
        $house = pdo_fetch("select * from ".tablename("kbwdl_house")." where id=:id",['id'=> $houseid]);
        
        $where =  ['houseid'=> $houseid, 'acttype'=> 'fav', 'uniacid'=> $uniacid, 'openid'=> $openid];
        $fav = pdo_fetch("select id from " . tablename("kbwdl_favorite") .
                " where houseid=:houseid AND acttype=:acttype  AND  uniacid=:uniacid AND openid=:openid",
                    $where
                );
        $smalltext = "";
        if($house['zhutype']==0){
            $smalltext = "{$house['village_name']} | {$house['room']}房{$house['hall']}厅{$house['garder']}卫 | {$house['superficie']}㎡ | {$house['loyer']}{$house['prix_unitaire']}" ;
        }
        $savedata = array(
            'uid' => $uid,
            'openid' => $openid,
            'uniacid' => $uniacid,
            'addtime' => TIMESTAMP,
            'houseid' => $houseid,
            'ftype' => $house['zhutype'], //收藏的房源类型
            'url'=> '',
            'acttype'=> 'fav',
            'hits'=> 1, //收藏成功
            'title' => $house['title'],
            'smalltext' =>  $smalltext,
            'jsondata'=> json_encode($jsondata)
        );
        if(!empty($_GPC['iscancel'])){
            //取消收藏
            pdo_update('kbwdl_favorite',['hits'=> 0, 'last_time'=> TIMESTAMP ], $where);
            pdo_update('kbwdl_house', ['fav_num -=' => 1], ['id' => $houseid ]);

            return $this->msg(1, "取消收藏" );

        }else {  
            if(empty($fav))      
           
                pdo_insert('kbwdl_favorite', $savedata);
            else
                pdo_update('kbwdl_favorite', $savedata, $where);
            
            /* 更新收藏数量 */
            pdo_update('kbwdl_house', ['fav_num +=' => 1], ['id' => $houseid ]);
            
        }   
                
        return $this->msg(1, "收藏成功" );
    
    }

    public function my()
    {
        $house  = new house($this->app);
        FrontHelper::check_login();
        /* 分页参数 */
        $page = max(1, $this->_GPC['page']);
        $pagesize = isset( $this->_GPC['pagesize'])? $this->_GPC['pagesize'] : 10;
        $startlimit = ($page - 1) * $pagesize;  
        $fileds =  $house->_query_sechouse_field();
        $uniacid = $this->uniacid;
        $openid = $this->openid;
        $lasttime = strtotime("-1 years");
        $condition = " uniacid='$uniacid' and isonline=1 and isdelete=0 ";
        $condition.= " AND id in( select houseid from ".tablename('kbwdl_favorite')." where acttype='fav' and openid='$openid' and addtime>'$lasttime' order by last_time desc ) ";
        $order = "refresh_time desc, update_time desc";
        $sql = "SELECT $fileds  FROM " . tablename("kbwdl_house") . " where $condition  order by $order limit $startlimit, $pagesize";
        $items = pdo_fetchall($sql);
        if (!empty($items)) {
            foreach ($items as $key => $item) {
                $val = $house->_format_sechouse($item);
                $items[$key] = $house->_format_show_item($val ) ;
            }
        }
        $data['total'] = pdo_fetchcolumn(" select count(*)  from ". tablename("kbwdl_house") . " where $condition ");
        $data['items'] = $items;
        $data['page'] = $page;
        $data['pagesize'] = $pagesize;
        return $this->msg(0, '我的收藏'.$sql, $data);
    }

    public function redpack()
    {
        FrontHelper::check_login();
        //红包功能待完善
        $data['total'] =  0;
        $data['items'] = [];
        $data['page'] = 1;
        $data['pagesize'] = 20;
        return $this->msg(0, '我的红包' , $data);
    }
    /**
     * 
     * 交易记录，暂未实现，主要是把后台的看房记录反馈给用户
     * @return array
     */
    public function feed()
    {
        FrontHelper::check_login();
        //红包功能待完善
        $data['total'] =  0;
        $data['items'] = [];
        $data['page'] = 1;
        $data['pagesize'] = 20;
        return $this->msg(0, '我的交易记录' , $data);
    }
    /**
     * 
     * 修改个人资料时检测
     * @return array
     */
    public function modifyuser(){
        FrontHelper::check_login();
        $broker = FrontHelper::get_broker();
        $_GPC = $this->_GPC;
        if(isset($_GPC['broker_id']) && $broker['id'] == $_GPC['broker_id'] ){

            try {
                Validate::make([
                    'avatar' => 'required', 
                    'nickname' => 'required',
                ], [
                    'mobile.required'   => '请输入手机号码',
                    'nickname.required'   => '请输入昵称', 
                ])->check( $_GPC );
            } catch (ValidateException $e) {            
                return $this->msg(1,  $e->getMessage() );
            }
            
            if(! FrontHelper::checkPostContent( $_GPC)){
                return $this->msg(1, '安全检查失败' );
            }
            pdo_update("kbwdl_broker", [
                'nickname' => $_GPC['nickname'],
                'avatar'  => $_GPC['avatar']
            ], array('id'=> $broker['id']));

            $broker = FrontHelper::get_broker(); 
        }
        return $this->msg(0, 'ok',  $broker);
    }
}
